import pathlib


def remove_migrations(path: pathlib.Path):
    # --------------------删除迁徙文件
    migrations = pathlib.Path(path, 'migrations')
    for migration in migrations.iterdir():
        if migration.is_dir() or migration.name.startswith('__init__'):
            continue
        migration.unlink()


def generate_views(path: pathlib.Path, m: str):
    with path.joinpath('views.py').open('w', encoding='utf-8') as f:
        f.write(f"""
from rest_framework import viewsets

from .models import {m}
from .serializers import {m}Serializer


class {m}ViewSet(viewsets.ModelViewSet):
    '''
    list: 查询所有{m}
    create: 新增{m}
    retrieve: 查询单个{m}, 文档名: read,接口名: retrieve
    update: 更新{m}
    destroy: 删除{m}
    '''
    queryset = {m}.objects.all()
    serializer_class = {m}Serializer
    
    def perform_create(self, serializer):
        serializer.save()

""")


def generate_urls(path: pathlib.Path, m: str):
    with path.joinpath('urls.py').open('w', encoding='utf-8') as f:
        f.write(f"""
from django.urls import path, include
from rest_framework.routers import DefaultRouter

from .views import {m}ViewSet


router = DefaultRouter()
router.register(r'', {m}ViewSet)

urlpatterns = [
    path('', include(router.urls)),
]


""")


def generate_serializer(path: pathlib.Path, m: str):
    with path.joinpath('serializers.py').open('w', encoding='utf-8') as f:
        f.write(f"""
from rest_framework import serializers
from .models import {m}


class {m}Serializer(serializers.ModelSerializer):
    class Meta:
        model = {m}
        fields = '__all__'

""")


def generate_admin(path: pathlib.Path, m: str):
    with path.joinpath('admin.py').open('w', encoding='utf-8') as f:
        f.write(f"""
from django.contrib import admin

# Register your models here.
from .models import {m}

admin.site.register({m})

        """)


def refresh_urls(root_path: pathlib.Path, children: list[str]):
    with root_path.joinpath(root, 'urls.py').open('w', encoding='utf-8') as f:
        f.write('''
from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView
from rest_framework.documentation import include_docs_urls
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
    path('', RedirectView.as_view(url='admin/')),
    path('admin/', admin.site.urls),
    path('docs/', include_docs_urls(title='API文档')),
    path('silk/', include('silk.urls', namespace='silk')),
    path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
''' + ''.join([f'    path("{c}/", include("{c}.urls")),\n'
               for c in children]) + '''
]
    ''')


root_dic = pathlib.Path(__file__).parent.absolute()
root = root_dic.name

children = []
for child in root_dic.iterdir():
    if child.is_dir() and child.name not in (root, 'static'):
        children.append(child.name)
        m = ''.join([
            c.capitalize()
            for c in child.name.replace('ies', 'y').rstrip('s').split('_')
        ])

        print(child, m)
        remove_migrations(child)
#         generate_views(child, m)
#         generate_urls(child, m)
#         generate_serializer(child, m)
#         generate_admin(child, m)

# refresh_urls(root_dic, children)
